/*
 * Copyright (c) 2021 柯华栋
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ipc_client.h"
#include <stdio.h>

static void on_update(gpointer* ud, ipc_map_t* map)
{
	(void)ud;
	// 打印参数
	g_print("\n\t\tON_UPDATE\n");
	g_print("id = %s\n", ipc_map_get_id(map));
	g_print("value = %s\n", ipc_map_get_string_value(map));
}

ipc_observer_t observer = {on_update, NULL};

// 测试
static void test_mcu(void)
{	
	ipc_map_t* map = ipc_map_new_id_string("mcu.version", "Hello World To Mcu Server");
	
	// 附加另外一个名字叫"strs"的key
	const gchar*  strs[3] = {"HelloA", "HelloB", "HelloC"};
	ipc_map_set_string_array(map, "strs", ipc_string_array_new2(strs, 3));	

	// POST 异步发送
	client_post(map);
	map = NULL;

	// 同步发送并获取结果
	ipc_map_t* ret = client_send_string("mcu.version", "Hello World To MCU Server");
	g_print("GET THE RETURN value = %s\n", ipc_map_get_string_value(ret));
	ipc_map_unref(ret);

	// 添加监听器
	client_add_observer("mcu.version", &observer);
}


// 测试
static void test_radio(void)
{
	// 异步发送
	client_post_string("radio.version", "Hello World To Radio Server");
	
	// 同步发送并获取结果
	ipc_map_t* ret = client_send_string("radio.version", "Hello World To Radio Server");
	g_print("GET THE RETURN value = %s\n", ipc_map_get_string_value(ret));
	ipc_map_unref(ret);
	
	// 添加监听器
	client_add_observer("radio.version", &observer);
}

static void g_print_no_convert(const gchar *buf)
{
    fputs(buf, stdout);
}

int main()
{
	// 代码最开始的位置先调用ipc_init再调用client_init(非常重要!!!!!)
	ipc_init();
	client_init("clientA");
	
	// 多个模块公用一个连接(因为这多个模块在同一个server里面实现)
	// client_set_module_server_name("mcu", "mcu_radio");	
	// client_set_module_server_name("radio", "mcu_radio");
	
	// 测试可以发现中文乱码不是传输的问题
	printf("柯华栋ABC ---------------------\n");
	g_print("柯华栋ABC ---------------------\n");	
	
	// 可以这样解决g_print乱码问题
	g_set_print_handler(g_print_no_convert);
	g_print("柯华栋ABC ---------------------\n");	

	test_radio();
	test_mcu();

	GMainLoop* loop = g_main_loop_new(NULL, FALSE);
	g_main_loop_run(loop);
	g_main_loop_unref(loop);
}
